package cn.wolfcode.trip.base.admin.controller;

import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

//图片资源控制器
@RestController
@RequestMapping("images")
public class ImagesController {

    @Autowired
    private ServletContext servletContext;

    //新增资源,用post请求
    @RequestMapping(method = RequestMethod.POST)
    public Map upload(MultipartFile upload){

        //将图片上传视为map单位
        HashMap map = new HashMap<>();

        try {
            //servletContext.getRealPath("/upload")  找到upload文件夹的真实路径
            //放进工具类进行后续的操作
            String realPath = servletContext.getRealPath("/upload");

            //从工具类中取出处理完毕的图片地址 譬如/upload/xxx.jgp
            String imgUrl = UploadUtil.upload(upload, realPath);

            //把数据装进map,把map返回给前端
            //1   是工具要求返回的数字
            map.put("uploaded",1);
            map.put("url",imgUrl);

        } catch (Exception e) {
            map.put("uploaded",0);
            HashMap errormap = new HashMap<>();
            errormap.put("message",e.getMessage());
            map.put("error",errormap);

        }
        //返回新生成的图片url
        return map;
    }
}
